package com.mojo.jvm;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;

/**
 * 自定义类加载器
 *
 * @author <a href="mailto:mojo_jj@163.com">Mojo</a>
 */
public class HelloClassLoader extends ClassLoader {
    public static void main(String[] args) throws Exception {
        HelloClassLoader cl = new HelloClassLoader();
        Class<?> clazz = cl.findClass("Hello");
        //Object o1 = HelloClassLoader.class.getClassLoader().loadClass("com.mojo.jvm.Hello").newInstance();
        Method[] methods = clazz.getDeclaredMethods();
        System.out.println(methods.length);
        for (Method method : methods) {
            method.setAccessible(true);
            try {
                System.out.println(">>>" + method.getName());
                method.invoke(clazz.newInstance());
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
        }
        //System.out.println(o1);
        //System.out.println(o1);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String base64 = "yv66vgAAADQAHAoABgAOCQAPABAIABEKABIAEwcAFAcAFQEABjxpbml0PgEAAygpVgEABENvZGUB" +
                "AA9MaW5lTnVtYmVyVGFibGUBAAg8Y2xpbml0PgEAClNvdXJjZUZpbGUBAApIZWxsby5qYXZhDAAH" +
                "AAgHABYMABcAGAEAGCBIZWxsbyBjbGFzcyBpbml0aWFsaXplZAcAGQwAGgAbAQASY29tL21vam8v" +
                "anZtL0hlbGxvAQAQamF2YS9sYW5nL09iamVjdAEAEGphdmEvbGFuZy9TeXN0ZW0BAANvdXQBABVM" +
                "amF2YS9pby9QcmludFN0cmVhbTsBABNqYXZhL2lvL1ByaW50U3RyZWFtAQAHcHJpbnRsbgEAFShM" +
                "amF2YS9sYW5nL1N0cmluZzspVgAhAAUABgAAAAAAAgABAAcACAABAAkAAAAdAAEAAQAAAAUqtwAB" +
                "sQAAAAEACgAAAAYAAQAAAAYACAALAAgAAQAJAAAAJQACAAAAAAAJsgACEgO2AASxAAAAAQAKAAAA" +
                "CgACAAAACAAIAAkAAQAMAAAAAgAN";
        byte[] bytes = Base64.getDecoder().decode(base64);
        byte[] bs = {};
        try {
            Path path = Paths.get("E:\\project\\mojo-java\\mojo-jvm\\src\\main\\java\\com\\mojo\\jvm\\Hello.xlass");
            bs = Files.readAllBytes(path);
            for (int i = 0; i < bs.length; i++) {
                bs[i] = (byte) (255 - bs[i]);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        Class<?> clazz = defineClass(name, bs, 0, bs.length);
        return clazz;
    }
}
